const falseMsgList = $(`#falseMsgList`);
const msgContent = $(`#chat-content-wrap`);

var chat = {
    codeid: $('#conversation li').eq(0).attr('data-codeid'),
    type:  $('#conversation li').eq(0).attr('data-type'),
    name:  $('#conversation li').eq(0).attr('data-name'),
    head: $('#conversation li').eq(0).attr('data-head'),
    // 发送消息
    SendMsg:function () {
        var text = $(`#my_content`).html();
        var myhead = $("#myhead").attr('src');
        if (text == ''){
            layer.msg('请输入消息');
            return  false;
        }
        var msg = {
            'codeid':this.codeid,
            'name':this.name,
            'head':myhead,
            'content':text,
            'type':this.type
        };

        $.ajax({
            url:sedMsgURL,
            type:"post",
            data:msg,
            dataType:"json",
            success:function (data) {
                if (data.state != 'success'){
                    layer.msg(data.msg);
                    return false;
                }
                const moban = `<div class="chat-msg my_msg msg_right">
                            <div class="my_icon">
                                <img src="${data.data.head}" class="people-online-img">
                            </div>
                            <div class="message-time-tip">
                                <span>${data.data.insetrt_time}</span>
                            </div>
                            <!---->
                            <div class="chat-msg-dialog">
                                <i class="msg-pointer"></i>
                                <div class="chat-msg-txt">
                                    ${text}
                                </div>

                            </div>
                        </div>`;

                // 将消息转发给某个人
                socket.send(JSON.stringify({
                    type: 'chatMessage' // 用于在服务端区分消息类型
                    ,data: data.data
                }));

                falseMsgList.html(moban);
                const child = falseMsgList.find(`> div`);
                child.appendTo(msgContent);
                let x = msgContent[0].scrollHeight;
                wrapScroll(x);
                $(`#my_content`).html(``);
                $(`#my_content`).focus();
                chat.updatelisiMsg( data.data);
                $("#conversation"+msg.codeid+" .liitem").html(msg.content);
                return false
            }
        });
    },
    // 初始化消息
    initmsgList:function () {
        msgContent.html('');
        this.initlist();
        var msg = {
            'codeid':this.codeid,
            'type' : this.type,
        };
        $.ajax({
            url:getMsgURL,
            type:"post",
            data:msg,
            dataType:"json",
            success:function (data) {
                if (data.state != 'success'){
                    layer.msg(data.msg);
                    return false;
                }
                $("#msgloading").remove();
                var msg = data.data;
                console.log(msg);
                var html = '';
                if (msg.length > 0){
                    for (var i = 0;i<msg.length;i++){
                        // 单聊
                        if (msg[i].type == 'friend'){
                            if (msg[i].mine == true){ // 自己的消息
                                html += '<div class="chat-msg my_msg msg_right">';
                                html += '<div class="my_icon">';
                                html += '<img src="'+msg[i].avatar+'" class="people-online-img">';
                                html += '</div><div class="message-time-tip"> <span>'+msg[i].insetrt_time+'</span></div>';
                                html += '<div class="chat-msg-dialog"> <i class="msg-pointer"></i><div class="chat-msg-txt">';
                                html += '<p>'+msg[i].message+'</p>';
                                html += '</div></div></div>';
                            }else {
                                html += '<div class="chat-msg my_msg">';
                                html += '<div class="my_icon">';
                                html += '<img src="'+msg[i].avatar+'" class="people-online-img">';
                                html += '</div><div class="message-time-tip"> <span>'+msg[i].insetrt_time+'</span></div>';
                                html += '<div class="chat-msg-dialog"> <i class="msg-pointer"></i><div class="chat-msg-txt">';
                                html += '<p>'+msg[i].message+'</p>';
                                html += '</div></div></div>';
                            }
                        }
                    }

                    falseMsgList.html(html);
                    const child = falseMsgList.find(`> div`);
                    child.appendTo(msgContent);
                    let x = msgContent[0].scrollHeight;
                    wrapScroll(x);
                    $(`#my_content`).focus();
                }

            }
        });

    },
    // 初始化加载loading
    initlist:function () {
        var html = '<div id="msgloading" >\n' +
            '<i id="layui-icon" class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>\n' +
            '</div>';
        msgContent.html(html);
    },
    // socket初始化
    socketInit:function () {
        socket.onopen = function () {
            console.log("WebSocket连接成功");
            socket.send(JSON.stringify({
                type: 'reg' //随便定义，用于在服务端区分消息类型
                ,data: {
                    'uid':uid
                }
            }));
        };

        // 监听得到消息
        socket.onmessage = function(res){
            var data = $.parseJSON( res.data);
            console.log(data);
            if (data.type == 'ping'){
                socket.send(JSON.stringify({
                     type: 'ping' //随便定义，用于在服务端区分消息类型
                    ,data: {}
                }));
            }else if (data.type == 'friend'){   // 单聊
                if (chat.codeid == data.send_uid){ // 如果当前页面是接受人的ID
                    var  html = '';
                    html += '<div class="chat-msg my_msg">';
                    html += '<div class="my_icon">';
                    html += '<img src="'+data.head+'" class="people-online-img">';
                    html += '</div><div class="message-time-tip"> <span>'+data.insetrt_time+'</span></div>';
                    html += '<div class="chat-msg-dialog"> <i class="msg-pointer"></i><div class="chat-msg-txt">';
                    html += '<p>'+data.send_message+'</p>';
                    html += '</div></div></div>';
                    falseMsgList.html(html);
                    const child = falseMsgList.find(`> div`);
                    child.appendTo(msgContent);
                    let x = msgContent[0].scrollHeight;
                    wrapScroll(x);
                    $(`#my_content`).focus();
                    $("#conversation"+data.send_uid+" .liitem").html(data.send_message);
                    $("#conversation"+data.send_uid+" .chat-msg-time").html(data.insetrt_time);
                }else { // 如果不是的话
                    $("#conversation"+data.send_uid+" .liitem").html(data.send_message);
                    $("#conversation"+data.send_uid+" #newmsg").addClass("newmsg");
                    $("#conversation"+data.send_uid+" .chat-msg-time").html(data.insetrt_time);
                }

            }
        };
        socket.onclose = function (res) {
            console.log(res);
        }
    },

    // 更新左侧消息列表
    updatelisiMsg:function (data) {
        // 更新历史窗口
        if ($("#conversation #conversation"+data.js_userid).length == 0){
            var html = '';
            html += '<li id="conversation'+data.js_userid+'" class="people-chat-list"  data-codeid="'+data.js_userid+'" data-type="'+data.type+'" data-name="'+data.name+'" data-head="'+data.jsname+'">';
            html += '<div><span class="head-img-wrap"><img src="'+data.jsname+'" class="people-online-img">';
            html += '<i id="newmsg"></i> </span></span><div class="chat-info-wrap"> <div class="chat-user"> <span class="user-right-icon"> </span>';
            html += ' <span class="chat-user-name">'+data.name+'</span> <span class="chat-msg-time">'+data.insetrt_time+'</span> </div>  <div class="chat-msg-info">';
            html += '  <span class="chat-last-msg liitem">'+data.send_message+'</span><div class="el-badge unread-item">   <sup class="el-badge__content el-badge__content--undefined" style="display: none;"></sup>';
            html += '   </div> </div> </div> </div> </li>';
            $("#conversation li").eq(0).before(html);
        }
    }
};

// 页面把聊天页面下移
function wrapScroll(h = 350) {
    const wrap = $(`#chat-content-wrap`);
    wrap.scrollTop(h);
}

$(function (){
    chat.initmsgList();
    chat.socketInit();

    // 监听聊天时间切换
    $('.people-chat-list').click(function() {
        $('.people-chat-list').removeClass(`active`);
        chat.codeid =  $(this).attr('data-codeid');
        chat.type =  $(this).attr('data-type');
        chat.name =  $(this).attr('data-name');
        chat.head =  $(this).attr('data-head');
        $("#chatname").html( chat.name);
        console.log(chat);
        $(this).addClass(`active`);
        $("#conversation"+chat.codeid+" #newmsg").removeClass("newmsg");
        chat.initmsgList();
    });

    // 发送消息
    $(`.my_send`).click(function() {
        chat.SendMsg();
    });

    //键盘发送
    $("#my_content").keyup(function(event){
        if(event.ctrlKey && event.keyCode == 13){
            chat.SendMsg();
            return false;
        }
    });
});
